<!-- 应付单 -->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper">
            <!-- 按钮 -->
            <div class="btn-wrapper clearfix">
                <btns-wrapper @searchClick="searchClick" :showModel="showModel" :orderId="orderId" :voucherState="voucherState" :editMask="editMask" @printOrder="printOrder" @switchList="switchList" @submitServer="submitServer" @clickEdit="clickEdit" @deleteOrder="deleteOrder" @getIdByData="getIdByData" @auditClick="auditClick" @turnThePage="turnThePage" @syncOrder="syncOrder" @submitOrder="submitOrder" @exportDetail="exportDetail" :sourceCode="sourceCode" @verificationFun="verificationFun">
                    <template slot="neworder">
                        <a-dropdown class="btns" key="new" style="display:block">
                            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增
                                    <a-icon type="down" style="color:rgb(24,144,255);vertical-align:middle;" />
                                </div>
                            </a>
                            <a-menu slot="overlay">
                                <a-menu-item key="0">
                                    <a href="javascript:void(0)" @click="newForecast">新增</a>
                                </a-menu-item>
                                <a-menu-item key="1">
                                    <a href="javascript:void(0)" @click="choiceBillsFromPurchaseInvoice">选采购发票</a>
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </template>
                    <template slot="shengdan">
                        <a-dropdown class="btns" key="sheng" style="display:block">
                            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                <a-icon class="btns-icon" type="snippets" />
                                <div class="btns-text">生单
                                    <a-icon type="down" />
                                </div>
                            </a>
                            <a-menu v-if="voucherState==1" slot="overlay">
                                <a-menu-item key="0">
                                    <a href="javascript:void(0)" @click="templateShow">生成凭证</a>
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </template>
                </btns-wrapper>
            </div>
            <div ref="print" class="documents-wrapper" id="documents-wrapper">
                <h3 class="text-center">
                    {{voucherTitle}}
                </h3>
                <section v-show="showModel=='list'">
                    <!--列表-->
                    <dynamicList ref="dyList" :basePostData="basePostData" :sourceCode="sourceCode" @switchList="switchList" @dblclick="getIdByData" :reportCode="reportCodeList"></dynamicList>
                </section>
                <section v-show="showModel=='order'">
                    <div><span class="audit-status" v-show="voucherState==0">待审核</span><span class="audit-status" v-show="voucherState==1 || voucherState==10">{{voucherState==1?'已审核':'关闭'}}</span></div>
                    <a-form-model :layout="formLayout">
                        <div class="header-box">
                            <order-dynamic-form :FormData="orderHeaderData" @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <div class="edit-mask-header" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                        <div class="table-box">
                            <a-table id="bills_tb" :columns="columns" :data-source="dataSource" :customRow="customClick" :scroll="{ x: 1000, y: 347 }" :pagination="false" @change="onTableChange" :size="small" bordered>
                                <template slot="number" v-if="isRouterAlive" slot-scope="text, record, index">

                                    <div v-if="index == dataSource.length-1">
                                        合计
                                    </div>
                                    <div v-else>
                                        {{index+1}}
                                    </div>
                                </template>
                                <template v-for="col in slotArray" :slot="col" slot-scope="text, record,index">
                                    <div data-key="">
                                        <editable-cell v-if="isRouterAlive" :sourceCode="sourceCode" :text="text" :col="col" :index="index" :record="record" :dataSource="dataSource" :dynamicAllData="dynamicFormData" :dynamicFormDataMap="dynamicFormDataMap"  :unitsDataDetails="unitsDataDetails" :unitsAssistSelect="unitsAssistSelect" @change="onCellChange(index, col, $event)" @choiceAddData="choiceAddData(index,col,$event)" @newAddData="handleAdd" />
                                    </div>
                                </template>
                            </a-table>
                            <div class="edit-mask" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                        <div class="footer-box">
                            <order-dynamic-form :FormData="orderFooterData"  @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <div class="edit-mask-footer" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                    </a-form-model>
                    <h4 class="margin-top-10">付款计划:</h4>

                    <a-table :columns="planColumns" :customRow="customClickPlan" :data-source="planDataSource" :scroll="{ x: 1000, y: 347 }" :pagination="false" :size="small" bordered>
                        <template v-for="col in planSlotArray" :slot="col" slot-scope="text, record,index">
                            <div data-key="">
                                <!-- <editable-cell v-if="isPlanRouterAlive" :sourceCode="sourceCode" :text="text" :col="col" :index="index" :record="record" :dataSource="planDataSource" :dynamicAllData="dynamicPlanFormData" :unitsDataDetails="unitsDataDetails" :unitsAssistSelect="unitsAssistSelect" @change="onCellChange(index, col, $event,'plan')" @choiceAddData="choiceAddData(index,col,$event)" @newAddData="handleAdd" /> -->
                                <editable-cell-plan v-if="isPlanRouterAlive" :record="record" :col="col" :text="text" @change="onCellChangePlan(index, col, $event)" />
                            </div>
                        </template>
                    </a-table>
                </section>

                <section v-show="showModel=='detail'">
                    <!--明细-->
                    <dynamicListDetails ref="detailSearchRef" :reportCode="reportCodeDetail" :componentType="1" :basePostData="basePostData"></dynamicListDetails>
                </section>
                <section v-show="showModel=='statistical'">
                    <!--统计-->
                    <dynamicListDetails ref="statisticalSearchRef" :reportCode="reportCodeStatistical" :componentType="2" :basePostData="basePostData"></dynamicListDetails>
                </section>
            </div>
            <div class="contextmenu-box">
                <!-- 右键菜单 -->
                <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                    <li @click="handleAdd()">新增行</li>
                    <li @click="handleDelete()">删除行</li>
                    <!-- <li @click="handleCopy()">复制行</li> -->
                </ul>
            </div>
            <drawerBox ref="searchList" :unitData="unitData" :unitsData="unitsData" :unitsDataDetails="unitsDataDetails" @editClickOrder="editClickOrder"></drawerBox>
            <div class="contextmenu-box">
                <!-- 还款计划右键菜单 -->
                <ul v-show="visiblePlan" :style="{left:leftmin+'px',top:topmin+'px'}" class="contextmenu">
                    <li @click="handleAddPlan()">新增行</li>
                    <li @click="handleDeletePlan()">删除行</li>
                    <!-- <li @click="handleCopy()">复制行</li> -->
                </ul>
            </div>
        </div>

        <!--加载中-->
        <div class="loading-wrapper" v-show="loading">
            <a-spin class="loading-content" tip="加载中..." />
        </div>
        <!--用做横向打印-->
        <!-- <div v-html="stylePrint"></div> -->
        <print-modal ref="printDom" v-if="printVisible" :incomingPrintData="incomingPrintData" @cancelPrint="cancelPrint"></print-modal>

        <!--生单成为凭证 -->
        <a-modal :visible="templateVisible" title="选择凭证模板" @cancel="templateCancel" @ok="templateOk" :width="800">
            <a-table style="min-height:200px" :data-source="templateFinanceData" :columns="templateColumns" :scroll="{ x: 1000, y: 200 }" :customRow="customClickTemplate" :row-selection="{ selectedRowKeys: selectedTemplateKeys, onChange: onSelectTemplateChange,columnWidth:40,type:'radio' }" :pagination="false" bordered>

            </a-table>
            <p>凭证明细</p>
            <a-table style="min-height:300px" :columns="columnsModal" :data-source="templateDetails" :scroll="{ x: 1000, y: 300 }" :pagination="false" bordered>

            </a-table>
        </a-modal>
    </div>
</template>
<script>

import { save, examine, remove, getCode, getPlanListApi, submitOrder } from '@/api/finance/receiveManagement/receivableVoucher'
import pro from '@/mixins/procurement/pro';
import editableCellPlan from "../accounting/editTable/EditableCell";
export default {
    mixins: [pro],
    components: {
        editableCellPlan
    },
    data () {
        return {
            //基础 查询条件（列表 + 翻页）
            basePostData: {
                someBusinessType: null,
                dataSource: 'PayableVoucher',
                beginStartFlag: 0,
            },
            sourceCode: 'PayableVoucher',
            reportCodeDetail: 'PayableVoucher_Detail_Report',
            reportCodeStatistical: 'PayableVoucher_Statistic_Report',   //统计code 
            reportCodeList: 'PayableVoucher_List_Report',              //列表code  
            financeType: 2,         //类型1应收 2应付
            beginStartFlag: 0,       //期初标识0:否 1:是

            //==============计划数据==================
            planDataSource: [],
            planColumns: [{
                title: '序号',
                key: 'number',
                dataIndex: 'number',
                width: 30,
                align: 'center',
            }, {
                title: '计划付款日期',
                key: 'planDate',
                dataIndex: 'planDate',
                width: 100,
                align: 'lect',
                scopedSlots: { customRender: 'planDate' },

            }, {
                title: '应还比例',
                key: 'proportion',
                dataIndex: 'proportion',
                width: 100,
                align: 'left',
                scopedSlots: { customRender: 'proportion' },
            }, {
                title: '应还金额',
                key: 'amount',
                dataIndex: 'amount',
                width: 100,
                align: 'right',
                scopedSlots: { customRender: 'amount' },
            }, {
                title: '采购订单号',
                key: 'orderNo',
                dataIndex: 'orderNo',
                width: 100,
                align: 'left',
                scopedSlots: { customRender: 'orderNo' },

            }],
            planSlotArray: ['proportion', 'amount', 'planDate', 'orderNo'],
            isPlanRouterAlive: true,

            visiblePlan: false,
            leftmin: 0,
            topmin: 0,
            thisClickPlanId: null,
            thisClickPlanRecord: null,
            countPlan: 0,
            planDataLenth: 8,    //初始多少条
            customClickPlan: (record, index) => ({
                on: {
                    contextmenu: (e) => {//右键事件
                        e.preventDefault();
                        this.openMenuPlan(e);
                        console.log('右键点击的', index, e);
                        this.thisClickPlanId = index;
                        this.thisClickPlanRecord = record;
                    },
                }
            })
        };
    },
    created () {
        //this.getIdByData();//获取最新一条数据

        //获取还款计划数据
        if (this.orderId) {
            setTimeout(() => {
                this.getlistInPlan();
            }, 500)
        }
    },
    mounted () {
        this.initPlan();
    },
    methods: {
        initPlan () {
            //初始化计划表
            this.planDataSource = [];
            this.reloadPlan();
            for (let index = 0; index < this.planDataLenth; index++) {
                let arr = {
                    number: index + 1,
                }
                this.planDataSource.push(arr)
            }
        },
        reloadPlan () {
            this.isPlanRouterAlive = false;
            this.$nextTick(function () {
                this.isPlanRouterAlive = true;
            });
        },
        //新增预测单
        newForecast () {
            this.showModel = 'order';
            this.editMask = false;
            this.loading = false;
            this.voucherState = -1;
            this.sourceVoucherData = {};//清空来源数据
            this.initForm(1);
            this.initPlan();
        },
        //保存
        submit (requestData) {
            requestData.type = this.financeType;
            requestData.dataSource = this.sourceCode;
            requestData.beginStartFlag = this.beginStartFlag;

            //还款计划
            let planData = _.cloneDeep(this.planDataSource);
            planData.forEach(item => {
                delete item.number;
            });
            let array = [];
            planData.forEach(item => {
                if (item.amount != 0 && item.amount != null) {
                    item.type = 2;//类型:1收款 2付款
                    array.push(item)
                }
            });
            if (array.length == 0) {
                this.$message.warning('付款计划必须填写');
                this.isSaveRun = true;
                return;
            }
            requestData.planList = array;
            save(requestData).then(response => {
                if (response.code === 200) {
                    this.$message.success('保存成功');
                    this.editMask = true;
                    this.isSaveRun = true;
                    if (!this.orderId) {
                        this.getIdByData(); //获取最新一条数据
                    }
                } else {
                    this.$message.error(response.message);
                    this.isSaveRun = true;
                }
            }).catch((e) => {
                this.isSaveRun = true;
            })
        },
        //单据提交
        submitOrder (type) {
            let data = {
                id: this.orderId,
                status: type,//状态 -1:撤回提交,0:提交
            }
            console.log(this.orderId);
            if (!this.orderId) {
                this.$message.warning('该单据未保存不需要提交');
                return;
            }
            if (this.voucherState == -1 && type == -1) {
                this.$message.warning('该单据未提交无需撤回提交');
                return;
            }
            submitOrder(data).then(res => {
                if (res.code === 200) {
                    if (type == 0) {
                        this.$message.success('提交成功');
                    } else {
                        this.$message.success('撤回提交成功');
                    }
                    this.getIdByData();
                }
            })
        },
        //审核
        auditClick (type) {
            let requestData = {
                id: this.orderId,
                status: type
            }
            examine(requestData).then((response) => {
                if (response.code === 200) {
                    const backData = response.data;
                    if (type == 1) {
                        this.$message.success('审核成功');
                        this.getIdByData();
                    }
                    if (type == 0) {
                        this.$message.success('弃审成功');
                        this.getIdByData();
                    }
                } else {
                    // this.$message.warning(response.message);
                }
            })
        },
        //删除
        remove (postData) {
            remove(postData).then(response => {
                if (response.code === 200) {
                    this.$message.success('删除成功');
                    this.orderId = '';
                    this.voucherState = 0;
                    this.getIdByData();//获取最新一条数据
                } else {
                    this.$message.error(response.message);
                }
            })
        },
        //获取单据编号
        getCode () {
            getCode({ sourceCode: this.sourceCode }).then((res) => {
                if (res.code == 200) {
                    console.log(res);
                    this.receiptNumber = res.message;
                    console.log(this.orderHeaderData)
                    for (let i = 0; i < this.orderHeaderData.length; i++) {
                        if (this.orderHeaderData[i].code == 'voucherCode') {
                            this.$set(this.orderHeaderData[i], 'onEdit', false)
                            this.$set(this.orderHeaderData[i], 'value', this.receiptNumber)
                        }
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            });
        },
        //选采购发票
        choiceBillsFromPurchaseInvoice () {
            let postData = {
                sourceCode: 'PurchaseInvoice',      // 来源单
                title: '选采购发票',
                dataSource: "PurchaseInvoice",
                businessType: 2, //1:退货业务 2：非退货业务 3: 退货 + 非退货 4: 发票
                someBusinessType: null,    // 指定业务类型 默认 0
                startVoucherState: 0,
                endVoucherState: null
            }
            this.$refs.searchList.onOpenBox(postData);
        },
        onCellChangePlan (indexTable, dataIndex, value) {
            //当前点击的行下标
            this.currentIndexTable = indexTable;
            console.log('当前点击的数据：', value);
            if (!value) {
                return;
            }
            const planDataSource = [...this.planDataSource];
            const target = planDataSource.find((item, index) => index === indexTable);
            if (dataIndex == 'crmName' || dataIndex == 'phonetic') {
                target['crmName'] = value.crmName;
                target['crmId'] = value.id;
                target['phonetic'] = value.phonetic;
                target['isEndNode'] = true;

            } else if (dataIndex == 'beginAmount') {
                //期初金额
                target[dataIndex] = value;

            } else if (value.columnType == '日期') {
                target[dataIndex] = value.value;
            } else {
                target[dataIndex] = value;
            }

            this.$nextTick(() => {
                this.totalInitialBalance = 0;
                planDataSource.forEach(item => {
                    this.totalInitialBalance = Number(this.totalInitialBalance) + Number(item.beginAmount ? item.beginAmount : 0);
                });
                this.planDataSource = planDataSource;
                this.reloadPlan();
            })
        },
        getlistInPlan () {
            //获取还款计划数据
            let data = {
                type: 2,//类型:1收款 2付款
                orderId: this.orderId
            }
            getPlanListApi(data).then(res => {
                if (res.code === 200) {
                    res.data.forEach((item, index) => {
                        item.number = index + 1;
                    });
                    this.planDataSource = res.data;
                    this.reloadPlan();
                }
            })

        },









        openMenuPlan (e) {
            //显示右键菜单
            var x = e.pageX - 250;
            var y = e.pageY - 40;
            this.topmin = y;
            this.leftmin = x;
            this.visiblePlan = true;
        },
        closeMenuPlan () {
            //隐藏右键菜单
            this.visiblePlan = false;
        },
        handleAddPlan () {
            //新增数据
            const { countPlan, planDataSource } = this;
            const newData = {
                number: countPlan + 1,
            };
            this.$nextTick(() => {
                this.planDataSource.splice(this.planDataSource.length, 0, newData);
                // this.$refs.print.scrollTo(0, 500)
                // document.getElementsByClassName('documents-wrapper').scroll(0, 500)
                // document.getElementById('documents-wrapper').scroll(0, this.$refs.print.scrollHeight)
                this.reloadPlan();
            })
        },
        handleDeletePlan () {
            //删除整行
            let _this = this;
            let numberId = this.thisClickPlanId;
            this.$confirm({
                title: "确认",
                content: (
                    <span>
                        您确定要{<span style="color:red;">删除</span>}该记录吗？
                    </span>
                ),
                onOk () {
                    let dataSource = [..._this.planDataSource];

                    if (dataSource.length - 1 > _this.planDataLenth) {
                        //大于规定行数(删除)
                        _this.planDataSource = dataSource.filter((item, index) => index !== numberId);
                    } else {
                        //小于规定行数(清空)
                        for (let i = 0; i < dataSource.length; i++) {
                            if (i === numberId) {
                                for (const key in dataSource[i]) {
                                    if (key != 'number') {
                                        dataSource[i][key] = null;
                                    }
                                }
                            }
                        }
                        _this.planDataSource = dataSource;
                    }
                    _this.reloadPlan();
                },
                onCancel () { },
            });
        },
    },
    watch: {
        visiblePlan (value) {
            if (value) {
                document.body.addEventListener("click", this.closeMenuPlan);
            } else {
                document.body.removeEventListener("click", this.closeMenuPlan);
            }
        },
        planDataSource (value) {
            this.countPlan = value.length;
        },
    }
};
</script>
<style lang="less">
    @import '~@/style/purchase/voucher.less';
</style>